<template>
  <div class="pagination">
    <button :disabled="pageNo===1" @click="$emit('newPageNo',pageNo-1)">上一页</button>
    <button v-show="startEndPages.start > 1" @click="$emit('newPageNo',1)">1</button>

    <button v-show="startEndPages.start > 2">···</button>
<!-- v-for和v-if不要同时去写，因为v-for优先级高与v-if，性能太差-->
<!--    <button
        v-for="page in startEndPages.end"
        :key="page"
        v-if="page >= startEndPages.start"
    >{{ page }}
    </button>-->
    <button
        v-for="page in startEndArr"
        :key="page"
        :class="{ active: pageNo === page }"
        @click="$emit('newPageNo',page)"
    >{{ page }}
    </button>

    <button v-show="startEndPages.end<totalPages-1">···</button>
    <button v-show="startEndPages.end<totalPages" @click="$emit('newPageNo',totalPages)">{{ totalPages }}</button>
    <button
        :disabled="pageNo === totalPages"
        @click="$emit('newPageNo',pageNo+1)"
    >下一页</button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ['pageNo', 'totalPages', 'continuousPage','total'],
  /*
  * 1.pageNo:当前页码
  * 2.totalPages:最大页数
  * 3.continuousPage:连续页数
  * */
/*  mounted() {
    setTimeout(() => {
      console.log('start', this.startEndPages.start, 'totalPages', this.startEndPages.end)
    }, 2000)
  },*/
  computed: {
    //通过计算属性,优先把需要遍历的页码计算出来
    startEndArr(){
      const arr = []
      for (let i = 1;i<=this.startEndPages.end;i++){
        if (i>=this.startEndPages.start){
          arr.push(i)
        }
      }
      return arr
    },
    startEndPages() {
      const {totalPages, pageNo, continuousPage} = this;
      let start = 0
      let end = 0
      //计算初始页码和结束页码
      //当连续页大于等于最大页码的时候
      if (totalPages < continuousPage) {
        start = 1
        end = totalPages
        //  当连续页小于最大页码的时候
      } else {
        start = pageNo - Math.floor(continuousPage / 2)
        end = pageNo + Math.floor(continuousPage / 2)
        //当计算出来的初始页码小于1的时候重置页码
        if (start < 1) {
          start = 1
          end = continuousPage
        }
        //当计算出来的最终页码大于最大页码的时候重置页码
        if (end > totalPages) {
          start = totalPages - continuousPage + 1
          end = totalPages
        }
      }
      return {start, end}
    }
  }
}
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>